#!/usr/bin/env python3
"""
生成测试数据的脚本
"""
import json
import random
import string
from datetime import datetime, timedelta
from pathlib import Path


def generate_user_data(num_users: int = 100) -> list:
    """生成用户测试数据"""
    users = []
    
    for i in range(1, num_users + 1):
        user = {
            "id": i,
            "username": f"test_user_{i}",
            "email": f"user{i}@example.com",
            "first_name": random.choice(["张", "李", "王", "刘", "陈"]),
            "last_name": random.choice(["三", "四", "五", "六", "七"]),
            "phone": f"1{random.randint(3000000000, 3999999999)}",
            "created_at": (datetime.now() - timedelta(days=random.randint(1, 365))).isoformat(),
            "is_active": random.choice([True, False]),
            "role": random.choice(["user", "admin", "moderator"])
        }
        users.append(user)
    
    return users


def generate_product_data(num_products: int = 50) -> list:
    """生成商品测试数据"""
    products = []
    categories = ["electronics", "clothing", "books", "home", "sports"]
    
    for i in range(1, num_products + 1):
        product = {
            "id": i,
            "name": f"测试商品 {i}",
            "category": random.choice(categories),
            "price": round(random.uniform(10.0, 1000.0), 2),
            "stock": random.randint(0, 1000),
            "description": f"这是第 {i} 个测试商品的描述",
            "created_at": (datetime.now() - timedelta(days=random.randint(1, 365))).isoformat(),
            "rating": round(random.uniform(1.0, 5.0), 1),
            "tags": [f"tag_{j}" for j in range(1, random.randint(2, 6))]
        }
        products.append(product)
    
    return products


def generate_order_data(num_orders: int = 200, num_users: int = 100, num_products: int = 50) -> list:
    """生成订单测试数据"""
    orders = []
    statuses = ["pending", "paid", "shipped", "delivered", "cancelled"]
    
    for i in range(1, num_orders + 1):
        user_id = random.randint(1, num_users)
        num_items = random.randint(1, 5)
        
        order_items = []
        total_amount = 0.0
        
        for j in range(num_items):
            product_id = random.randint(1, num_products)
            quantity = random.randint(1, 10)
            price = round(random.uniform(10.0, 500.0), 2)
            subtotal = round(price * quantity, 2)
            
            order_items.append({
                "product_id": product_id,
                "quantity": quantity,
                "price": price,
                "subtotal": subtotal
            })
            
            total_amount += subtotal
        
        order = {
            "id": i,
            "user_id": user_id,
            "total_amount": round(total_amount, 2),
            "status": random.choice(statuses),
            "created_at": (datetime.now() - timedelta(days=random.randint(1, 365))).isoformat(),
            "shipping_address": f"测试地址 {random.randint(1, 1000)}号",
            "order_items": order_items
        }
        orders.append(order)
    
    return orders


def generate_sorting_test_data() -> dict:
    """生成排序算法测试数据"""
    test_cases = {
        "empty_list": [],
        "single_element": [42],
        "small_sorted": [1, 2, 3, 4, 5],
        "small_reverse_sorted": [5, 4, 3, 2, 1],
        "small_random": [3, 1, 4, 2, 5],
        "with_duplicates": [5, 2, 8, 2, 5, 8, 1],
        "negative_numbers": [-3, -1, -7, -2, -5],
        "mixed_numbers": [-5, 10, -3, 7, -1, 15],
        "large_random": [random.randint(1, 10000) for _ in range(1000)],
        "already_sorted_large": list(range(1, 1001)),
        "reverse_sorted_large": list(range(1000, 0, -1)),
        "float_numbers": [random.uniform(0, 100) for _ in range(100)],
        "string_list": [''.join(random.choices(string.ascii_letters, k=5)) for _ in range(50)]
    }
    
    # 添加预期结果
    expected_results = {}
    for key, data in test_cases.items():
        if data:
            expected_results[key] = sorted(data)
        else:
            expected_results[key] = []
    
    return {
        "test_cases": test_cases,
        "expected_results": expected_results
    }


def save_data_to_file(data: dict, filename: str):
    """保存数据到文件"""
    output_dir = Path("fixtures/data/generated")
    output_dir.mkdir(parents=True, exist_ok=True)
    
    file_path = output_dir / filename
    
    with open(file_path, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    
    print(f"数据已保存到: {file_path}")


def main():
    """主函数"""
    print("开始生成测试数据...")
    
    # 生成用户数据
    print("生成用户数据...")
    users = generate_user_data(100)
    save_data_to_file(users, "generated_users.json")
    
    # 生成商品数据
    print("生成商品数据...")
    products = generate_product_data(50)
    save_data_to_file(products, "generated_products.json")
    
    # 生成订单数据
    print("生成订单数据...")
    orders = generate_order_data(200, 100, 50)
    save_data_to_file(orders, "generated_orders.json")
    
    # 生成排序测试数据
    print("生成排序测试数据...")
    sorting_data = generate_sorting_test_data()
    save_data_to_file(sorting_data, "sorting_test_data.json")
    
    # 生成测试配置文件
    print("生成测试配置文件...")
    config = {
        "database": {
            "test_url": "sqlite:///test.db",
            "fixtures": ["users", "products", "orders"]
        },
        "api": {
            "base_url": "http://localhost:8000",
            "timeout": 30
        },
        "testing": {
            "users_count": 100,
            "products_count": 50,
            "orders_count": 200
        }
    }
    save_data_to_file(config, "test_config.json")
    
    print("测试数据生成完成!")
    print("生成的文件:")
    print("- fixtures/data/generated/generated_users.json")
    print("- fixtures/data/generated/generated_products.json")
    print("- fixtures/data/generated/generated_orders.json")
    print("- fixtures/data/generated/sorting_test_data.json")
    print("- fixtures/data/generated/test_config.json")


if __name__ == "__main__":
    main()